package com.lienlq.voicemusic.entity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.lienlq.voicemusic.xmlprc.XMLRPCMethod;
import com.lienlq.voicemusic.xmlprc.XMLRPCMethodCallback;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.Parcelable;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

public class MusicService extends Service {
	static String uri_streams = new String();
	public static final String TRACK_LIST_NAME = "track_list";
	public static final String CURRENT_NOW_PLAYING_TRACK = "now-playing-track";
	public static final String CURRENT_NOW_PLAYING_ARTIST = "now-playing-artist";
	public static final String PLAYING_TRACK = "playing_track",
			NAVIGATIVE_MEDIA_STATE = "navigative_value";
	public static final int MSG_REGISTER_NOWPLAYING = 1;
	public static final int MSG_ACTIVED_NOWPLAYING = MSG_REGISTER_NOWPLAYING + 1;
	public static final int MSG_UPDATE_DATA_NOWPLAYING = MSG_ACTIVED_NOWPLAYING + 1;
	public static final int MSG_RECIEVED_TRACK_LIST = MSG_UPDATE_DATA_NOWPLAYING + 1;
	public static final int MSG_SEND_DATA_TO_SERVICE = 5;
	public static final int MSG_SEND_TO_NOWPLAYING = 6,
			MSG_NAVIGATIVE_MEDIA = 7, MSG_NOWPLAYING_TRACK = 8, 
					MSG_REGISTER_MAIN_ACTIVITY = 9;
	public static boolean isRunning = false;
	private boolean isPlaying = true;

	private Messenger nowPlayingMsg = null, mainActivityMsg  = null;

	String TAG = "ACTIVIY_LOG";
	public MediaPlayer mediaPlayer;
	public static ArrayList<Track> trackList = new ArrayList<Track>();
	private int currentTrack = 0;
	private boolean isExeption = false;

	private Messenger mMessageer = new Messenger(new MusicHandler());
	private Context mContext;

	private class MusicHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_ACTIVED_NOWPLAYING:
				nowPlayingMsg = msg.replyTo;
				sendDataToNowPlaying();
				break;
			case MSG_REGISTER_MAIN_ACTIVITY :
				mainActivityMsg = msg.replyTo;
				break;
			case MSG_RECIEVED_TRACK_LIST:
				Bundle b = msg.getData();
				ArrayList<Track> list = b
						.getParcelableArrayList(TRACK_LIST_NAME);
				if (list != null) {
					trackList = list;
				}
				currentTrack = b.getInt(PLAYING_TRACK);
				updateNowPlaying();
				sendCurrentNowPlayingToMainActivity();
				break;

			case MSG_NAVIGATIVE_MEDIA:
				if (msg.arg1 == -1) { // previous is pressed;
					currentTrack--;
					Log.i("MEDIA", "Previous is pressed");
				} else if (msg.arg1 == 1) { // next button is pressed;
					currentTrack++;
					Log.i("MEDIA", "Next is pressed");
				} else if (msg.arg1 == 100) {
					if (mediaPlayer.isPlaying()) {
						mediaPlayer.pause();
						isPlaying = false;
						Toast.makeText(mContext, "Táº¡m dá»«ng", Toast.LENGTH_SHORT)
								.show();
						Log.i("MEDIA", "Pause is pressed");
					} else {
						mediaPlayer.start();
						isPlaying = true;
						Log.i("MEDIA", "Play is pressed");
					}
					break;
				}
				updateNowPlaying();
				sendDataToNowPlaying();
				break;
			default:
				super.handleMessage(msg);
			}
		}
	}

	private void sendDataToNowPlaying() {
		Message msg = Message.obtain(null, MSG_UPDATE_DATA_NOWPLAYING);
		Bundle b = new Bundle();
		b.putParcelableArrayList(TRACK_LIST_NAME, trackList);
		b.putInt(PLAYING_TRACK, currentTrack);
		b.putBoolean(NAVIGATIVE_MEDIA_STATE, isPlaying);
		msg.setData(b);
		try {
			nowPlayingMsg.send(msg);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	private void sendCurrentNowPlayingToMainActivity() {
		if (mainActivityMsg == null) {
			Log.i("SERVICE", "mainActivityMsg == null");
			return;
		}
		Message msg = Message.obtain(null, MSG_NOWPLAYING_TRACK);
		Bundle bu = new Bundle();
		bu.putString(CURRENT_NOW_PLAYING_TRACK, trackList.get(currentTrack).getTrack());
		bu.putString(CURRENT_NOW_PLAYING_ARTIST, trackList.get(currentTrack).getArtist());
		msg.setData(bu);
		try {
			mainActivityMsg.send(msg);
		} catch (RemoteException e) { 
			Log.e("SERVICE", "mainActivityMsg == null" + e.toString());
			e.printStackTrace();
		}
	}

	public boolean getPlayingState() {
		return mediaPlayer.isPlaying();
	}

	public class MyBinder extends Binder {
		public MusicService getService() {
			return MusicService.this;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		Log.i(TAG, "MusicService is onBind");
		return mMessageer.getBinder();
	}

	@Override
	public void onCreate() {
		super.onCreate();
		if (mediaPlayer == null) {
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

				@Override
				public void onCompletion(MediaPlayer mp) {
					Log.i("MEDIA", "MediaPlayer is complete");
					if (isExeption == false) {
						currentTrack++;
						updateNowPlaying();
						sendDataToNowPlaying();
					}
				}
			});
		}
		mContext = this;
		isRunning = true;
		// Toast.makeText(this,MusicService.class.getName() + "onCreate",
		// Toast.LENGTH_LONG).show();
		Log.i(TAG, "Music Service is onCreate");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			mediaPlayer.release();
			mediaPlayer = null;
		}
		isRunning = false;
		Log.i(TAG, "Music Service is onDestroy");
		// Toast.makeText(this,MusicService.class.getName() + "onDestroy",
		// Toast.LENGTH_LONG).show();
	}

	@Override
	public void onLowMemory() {
		Toast.makeText(getApplicationContext(), "on low memory",
				Toast.LENGTH_SHORT).show();
		if (mediaPlayer != null) {
			if (mediaPlayer.isPlaying())
				mediaPlayer.stop();
			mediaPlayer.release();
			mediaPlayer = null;
		}
		super.onLowMemory();
		Log.i(TAG, "Music Service is onLowMemory");
		// Toast.makeText(this,MusicService.class.getName() + "onLowMemory",
		// Toast.LENGTH_LONG).show();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		Log.i(TAG, "Music Service is onStart");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(TAG, "MusicService is onStartCommand");
		return START_STICKY;
	}

	public void updateNowPlaying() {
		if (!isOnline()) {
			Toast.makeText(this, "Vui lÃ²ng báº­t káº¿t ná»‘i máº¡ng", Toast.LENGTH_LONG)
					.show();
			return;
		}
		if (currentTrack < 0 || currentTrack > trackList.size() - 1) {
			currentTrack = 0;
		}
		Track t = trackList.get(currentTrack);
		Toast.makeText(this, " Đang tải bài\"" + t.getTrack() + "\"",Toast.LENGTH_LONG).show();
		String uri_xml = t.getUri();

		// Chuyen link xml ve link stream de nghe nhac
		XMLRPCMethod method = new XMLRPCMethod("Crawler",new XMLRPCMethodCallback() {

					@Override
					public void CallFinished(Object result) {
						// TODO Auto-generated method stub
						uri_streams = result.toString();
						Log.i("MEDIA", "Stream Link : " + uri_streams);
						if (uri_streams.equals(null))
							return;

						new Thread() {
							@Override
							public void run() {
								super.run();
								try {
									isExeption = false;
									mediaPlayer.reset();
									mediaPlayer.setDataSource(uri_streams);
									mediaPlayer.prepareAsync();
									
								} catch (IllegalArgumentException e) {
									Log.e("MEDIA",
											MusicService.class.getName() + " " + e.toString());
									isExeption = true;
								} catch (IllegalStateException e) {
									Log.e("MEDIA",
											MusicService.class.getName() + " " + e.toString());
									isExeption = true;
								} catch (IOException e) {
									Log.e("MEDIA",
											MusicService.class.getName() + " " + e.toString());
									isExeption = true;
								}
								// }while(isExeption);
								mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
									@Override
									public void onPrepared(MediaPlayer mp) {
										mediaPlayer.start();
										int durationMusic = 0;
										durationMusic = mediaPlayer.getDuration();
										int minute = durationMusic / 1000 / 60;
										int second = durationMusic / 1000 % 60;
										Log.i("MEDIA", trackList.get(currentTrack).getTrack()
												+ " - duration : "
												+ (minute < 10 ? "0" + minute : minute) + ":"
												+ (second < 10 ? "0" + second : second));
									}
								});
							}
						}.start();
					}
				});
		Object[] params = { uri_xml };
		method.call(params);
		// end
		
		
	}

	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnectedOrConnecting()) {
			return true;
		}
		return false;
	}
}
